﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace System.DataProvider
{
    public interface IParamBuilder
    {
        SqlParameter[] BuildParamSet(StoredProc proc, object[] dataArray);
    }

    public class DefaultParamBUilder : IParamBuilder
    {
        public SqlParameter[] BuildParamSet(StoredProc proc, object[] dataArray)
        {
            int count = proc.paras.Count;
            SqlParameter[] param = new SqlParameter[count];
            for (int counter = 0; counter < count; counter++)
            {
                param[counter] = new SqlParameter("@" + proc.paras[counter].Name, dataArray[counter]);
            }
            return param;
        }
    }

    public class CSVParamBUilder : IParamBuilder
    {
        string[] keyValues = null;
        public SqlParameter[] BuildParamSet(StoredProc proc, object[] dataArray)
        {
            if (dataArray != null && dataArray[0] != null)
                keyValues = dataArray[0].ToString().Split('|');


            int count = proc.paras.Count;
            SqlParameter[] param = new SqlParameter[count];
            for (int counter = 0; counter < count; counter++)
            {
                string paranName = proc.paras[counter].Name;
                string value = ExtractParamValue(paranName);
                if (string.IsNullOrEmpty(value))
                    param[counter] = new SqlParameter("@" + paranName, DBNull.Value);
                else
                    param[counter] = new SqlParameter("@" + paranName, value);
            }
            return param;
        }

        private string ExtractParamValue(string key)
        {
            string returnValue = string.Empty;
            foreach (string keyValue in keyValues)
            {
                string[] data = keyValue.Split('=');
                if (data[0].ToLower() != key.ToLower())
                    continue;
                else
                    returnValue = data[1];
                break;
            }
            return returnValue;
        }
    }
}
